﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using System.Threading;
using System.Diagnostics;
using Microsoft.AspNet.Mvc.Rendering;
using System.IO;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Features.Internal;
using Microsoft.Security.Application;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace CardWarWEB.Controllers
{
    [Route("Interpreter")]
    public class InterpreterController : Controller
    {
        [Route("bbs/{a?}/{b?}/{c?}/{d?}/{e?}/{f?}/{g?}/{h?}/{i?}/{j?}/{k?}/{l?}/{m?}/{n?}/{o?}/{p?}/{q?}/{r?}/{s?}/{t?}/{u?}/{v?}/{w?}/{x?}/{y?}/{z?}")]
        public object bbs()
        {
            return "Building";
            string path = Request.Path.Value;
            path = path.Replace("Interpreter/bbs/", "");
            if (string.IsNullOrEmpty(path))
                return Redirect("/Error/403");

            if (!System.IO.File.Exists(Server.GetApplicationBasePath() + @"/wwwroot/bbs" + path))
                return Redirect("/Error/404");

            if (!path.EndsWith(".php"))
            {
                string ext = Path.GetExtension(path);
                string mime = "application/octet-stream";
                if (Conf.mappings.ContainsKey(ext))
                    mime = Conf.mappings[ext];
                string filename = Path.GetFileName(path);
                FileStream fs = new FileStream(Server.GetApplicationBasePath() + @"/wwwroot/bbs" + path, FileMode.Open, FileAccess.Read);
                return File(fs, mime, filename);

            }

            string iparams = "";
            foreach (var s in Request.Query)
            {
                iparams += s.Key + "=" + s.Value + "&";
            }
            if (!string.IsNullOrEmpty(iparams))
                iparams = iparams.Substring(0, iparams.Length - 1);
            string icookie = "";
            foreach (var s in Request.Cookies)
            {
                icookie += s.Key + "=" + s.Value + "&";
            }
            if (!string.IsNullOrEmpty(icookie))
                icookie = icookie.Substring(0, icookie.Length - 1);
            string ipost = "";
            /*
            foreach(var t in HttpContext.Features.ToArray())
            {
                Console.WriteLine(t.Key.FullName);

            }

    */

            var ss = HttpContext.Features.Get<IFormFeature>();
            var Post = ss.Form;
            if (Post != null)
            {
                foreach (var n in Post)
                {
                    ipost += n.Key + "=" + n.Value + "&";
                }
                if (!string.IsNullOrEmpty(ipost))
                    ipost = ipost.Substring(0, ipost.Length - 1);
            }




            //Console.WriteLine(ipost);

            string R = "";

            Process p = new Process();
            p.StartInfo.FileName = Server.GetApplicationBasePath() + "/PHP/php-cgi.exe";
            p.StartInfo.Arguments = "-q";
            p.StartInfo.EnvironmentVariables.Add("SERVER_PROTOCOL", "HTTP/1.1");
            p.StartInfo.EnvironmentVariables.Add("SERVER_PORT", "80");
            p.StartInfo.EnvironmentVariables.Add("REQUEST_METHOD", Request.Method.ToUpper());
            p.StartInfo.EnvironmentVariables.Add("PATH_INFO", path);
            p.StartInfo.EnvironmentVariables.Add("PATH_TRANSLATED", Server.GetApplicationBasePath() + @"/wwwroot/bbs" + path);
            p.StartInfo.EnvironmentVariables.Add("SCRIPT_NAME", path);
            p.StartInfo.EnvironmentVariables.Add("QUERY_STRING", iparams);
            p.StartInfo.EnvironmentVariables.Add("REMOTE_HOST", Request.Host.Value);
            p.StartInfo.EnvironmentVariables.Add("REMOTE_ADDR", Request.Host.Value);
            p.StartInfo.EnvironmentVariables.Add("CONTENT_TYPE", "application/x-www-form-urlencoded;charset=utf-8");
            p.StartInfo.EnvironmentVariables.Add("CONTENT_LENGTH", ipost.Length.ToString());
            p.StartInfo.EnvironmentVariables.Add("HTTP_COOKIE", icookie);
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = false;
            p.Start();
            p.StandardInput.WriteLine(ipost);

            R = p.StandardOutput.ReadToEnd();
            p.Dispose();
            /*
            string[] T = R.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            Console.WriteLine(R);
            R = "";
            bool skip = true;
            for (int i = 0; i < T.Length; i++)
            {
                if (skip && string.IsNullOrEmpty(T[i]))
                {
                    skip = false;
                    continue;
                }
                if (skip)
                {
                    string[] K = T[i].Split(new string[] { ":" }, StringSplitOptions.None);
                    if (Response.Headers.ContainsKey(K[0]))
                        Response.Headers[K[0]] += ";" + K[1];
                    else
                        Response.Headers.Add(K[0], K[1]);
                }
                if (!skip)
                    R += T[i] + "\r\n";
            }
            ViewBag.R = R;*/
            return R;

        }

        public IActionResult Index()
        {
            return Redirect("/Error/403");
        }



    }
}
